package com.umeng.soexample.mvp.view.fragment;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.umeng.lib_core.base.BaseFragment;
import com.umeng.soexample.R;
import com.umeng.soexample.ali_demo.PayDemoActivity;
import com.umeng.soexample.bean.AddCarEntity;
import com.umeng.soexample.bean.CarListEntity;
import com.umeng.soexample.bean.CollectionEntity;
import com.umeng.soexample.bean.SelGoodsValuesEntity;
import com.umeng.soexample.dao.USerService;
import com.umeng.soexample.di.compont.DaggerCarListFragmentCompont;
import com.umeng.soexample.di.modules.CarListFragmentModules;
import com.umeng.soexample.mvc.view.FragmentActivity;
import com.umeng.soexample.mvp.contract.CarListFragmentContract;
import com.umeng.soexample.mvp.persenter.CarListFragmentPresenter;
import com.umeng.soexample.mvp.view.adapter.CarListAdapter;
import com.umeng.soexample.mvp.view.adapter.CarListHeadAdapter;
import com.umeng.soexample.mvp.view.custom.MyTextViewHomeOriginalPrice;
import com.umeng.soexample.network.API;

import java.util.ArrayList;
import java.util.List;

/**
 * 购物车页面
 */
public class CarListFragment extends BaseFragment<CarListFragmentPresenter> implements CarListFragmentContract.CarListFragmentIView, View.OnClickListener,  CompoundButton.OnCheckedChangeListener {
    private SelGoodsValuesEntity selGoodsValuesEntity = null;
    private String user_id;
    private ImageView iv_car_list_back;
    private TextView tv_car_list_bj_wc;
    private boolean bj_wc = false;
    private RecyclerView rv_car_list;
    private CarListAdapter adapter;
    private GridLayoutManager gridLayoutManager;
    private CheckBox cb_car_list_qx;
    private boolean cbqx = true;
    private LinearLayout ll_goods_values_online_service;
    private TextView tv_car_list_sumprice;
    private LinearLayout ll_goods_values_brand_store;
    private Button btn_car_list_account;
    private LinearLayout ll_car_list_values;
    private LinearLayout ll_car_list_price;//显示总价
    private LinearLayout ll_car_list_save;//显示收藏
    private Button btn_car_list_add_save;
    private List<CarListEntity.ValuesBean> list = new ArrayList<>();
    private View view_head;
    private LinearLayout ll_item_head_car_list_0;//购物车为空
    private TextView tv_item_head_car_list_sbgg;
    private LinearLayout ll_item_head_car_list_1;//购物车不为空
    private RecyclerView rv_item_head_car_list;

    private CarListHeadAdapter headAdapter;
    private TextView tv_item_head_car_list_sum_price;//实时计算选中的总价
    //加入购物车
    private PopupWindow addcar_pop;
    private TextView tv_item_bottom_addcar_goods_size;//尺寸
    private TextView tv_item_bottom_addcar_num_number;//数量
    private int color;
    private CheckBox cb_item_bottom_addxar_size_l;
    private CheckBox cb_item_bottom_addxar_size_xl;
    private CheckBox cb_item_bottom_addxar_size_xxl;
    private CheckBox cb_item_bottom_addxar_size_xxxl;
    private int size;
    private CarListEntity.RecommendGoodsBean goodsBean = null;
    private int startCollection, endCollection;
    private String price;
    @Override
    public View createView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_car_list, null);
        return view;
    }

    @Override
    public void init(View view) {

        iv_car_list_back = view.findViewById(R.id.iv_car_list_back);
        tv_car_list_bj_wc = view.findViewById(R.id.tv_car_list_bj_wc);
        rv_car_list = view.findViewById(R.id.rv_car_list);
        cb_car_list_qx = view.findViewById(R.id.cb_car_list_qx);
        tv_car_list_sumprice = view.findViewById(R.id.tv_car_list_sumprice);
        btn_car_list_account = view.findViewById(R.id.btn_car_list_account);
        ll_car_list_values = view.findViewById(R.id.ll_car_list_values);
        ll_car_list_price = view.findViewById(R.id.ll_car_list_price);
        ll_car_list_save = view.findViewById(R.id.ll_car_list_save);
        btn_car_list_add_save = view.findViewById(R.id.btn_car_list_add_save);


        //头布局初始化
        view_head = View.inflate(getContext(), R.layout.item_head_car_list, null);
        ll_item_head_car_list_0 = view_head.findViewById(R.id.ll_item_head_car_list_0);
        tv_item_head_car_list_sbgg = view_head.findViewById(R.id.tv_item_head_car_list_sbgg);
        ll_item_head_car_list_1 = view_head.findViewById(R.id.ll_item_head_car_list_1);
        rv_item_head_car_list = view_head.findViewById(R.id.rv_item_head_car_list);
        tv_item_head_car_list_sum_price = view_head.findViewById(R.id.tv_item_head_car_list_sum_price);


        //主RecyclerView配置
        adapter = new CarListAdapter(R.layout.item_car_list);
        gridLayoutManager = new GridLayoutManager(getContext(), 2, GridLayoutManager.VERTICAL, false);
        rv_car_list.setLayoutManager(gridLayoutManager);

        //头RecyclerView配置
        headAdapter = new CarListHeadAdapter(R.layout.item_head_car_list_item);
        rv_item_head_car_list.setLayoutManager(new LinearLayoutManager(getContext()));
        rv_item_head_car_list.setAdapter(headAdapter);
        adapter.addHeaderView(view_head, 0);
        rv_car_list.setAdapter(adapter);
    }

    @Override
    public void initData() {

        Cursor cursor = USerService.getInstance().query("user", null, null);
        if (cursor.moveToNext()){
            user_id = cursor.getString(cursor.getColumnIndex("user_id"));
        }else{
            Toast.makeText(getContext(), "购物车 -> 数据库搜索用户失败", Toast.LENGTH_SHORT).show();
            return;
        }
        p.request(user_id, "1");
    }

    @Override
    public void setupDagger() {
        DaggerCarListFragmentCompont.builder().carListFragmentModules(new CarListFragmentModules(this))
                .build().inject(this);
    }

    @Override
    public void initListener() {
        iv_car_list_back.setOnClickListener(this);//返回上一页
        tv_car_list_bj_wc.setOnClickListener(this);//编辑/完成
        btn_car_list_account.setOnClickListener(this);//结算/删除
        btn_car_list_add_save.setOnClickListener(this);//移入收藏夹
        //全选按钮监听
        cb_car_list_qx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    for (CarListEntity.ValuesBean bean : list){
                        bean.shop_select = "1";
                    }
                }else{
                    if (cbqx){
                        for (CarListEntity.ValuesBean bean : list){
                            bean.shop_select = "0";
                        }
                    }
                    cbqx = true;
                }
                headAdapter.notifyDataSetChanged();
                isQXorSumPrice();
            }
        });

        /**
         * 购物车Headitem子控件监听
         */
        headAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                int viewId = view.getId();
                switch (viewId){
                    case R.id.cb_item_head_car_list_shop_select://是否选中
                        cbqx = false;
                        CheckBox checkBox = (CheckBox) view;
                        if (checkBox.isChecked()){
                            list.get(position).shop_select = "1";
                        }else{

                            for (CarListEntity.ValuesBean bean : list){
                                list.get(position).shop_select = "0";
                            }
                        }
                        isQXorSumPrice();
                        break;
                }
            }
        });

        /**
         * 购物车Headitem件监听
         */
        headAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                Intent goodsValues = new Intent(getActivity(), FragmentActivity.class);
                goodsValues.putExtra("type", "goods_values");
                goodsValues.putExtra("goods_id", headAdapter.getData().get(position).goods_id);
                getActivity().startActivity(goodsValues);
            }
        });

        /**
         * 购物车下方item
         */
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                Intent goodsValues = new Intent(getActivity(), FragmentActivity.class);
                goodsValues.putExtra("type", "goods_values");
                goodsValues.putExtra("goods_id", adapter.getData().get(position).goods_id);
                getActivity().startActivity(goodsValues);
            }
        });

        /**
         * 购物车下方item子控件
         */
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                switch (view.getId()){
                    case R.id.iv_item_car_list_add_to_car:
                        goodsBean = adapter.getData().get(position);
                        addcar_popupwindow(goodsBean);
                        break;
                }
            }
        });
    }

    @Override
    public void carListSuccess(CarListEntity entity) {
        if (entity.values.size() <= 0 || entity.values == null){
       // if ( entity.values == null){
            tv_car_list_bj_wc.setVisibility(View.GONE);
            ll_car_list_values.setVisibility(View.GONE);
            ll_item_head_car_list_1.setVisibility(View.GONE);
            ll_item_head_car_list_0.setVisibility(View.VISIBLE);
        }else{
            ll_item_head_car_list_0.setVisibility(View.GONE);
            tv_car_list_bj_wc.setVisibility(View.VISIBLE);
            ll_car_list_values.setVisibility(View.VISIBLE);
            ll_item_head_car_list_1.setVisibility(View.VISIBLE);
            List<CarListEntity.ValuesBean> valuesBeanList = new ArrayList<>();
            for (CarListEntity.ValuesBean waibean : entity.values){
                boolean you = true;
                for (CarListEntity.ValuesBean neibean : valuesBeanList){
                    if (neibean.goods_id.equals(waibean.goods_id)){
                        neibean.shop_num = Integer.parseInt(neibean.shop_num) + Integer.parseInt(waibean.shop_num) + "";
                        you = false;
                        break;
                    }
                }
                if (you){
                    valuesBeanList.add(waibean);
                }
            }
            list.clear();
            list.addAll(valuesBeanList);
            headAdapter.setNewData(list);
            isQXorSumPrice();
        }
        adapter.setNewData(entity.recommend_goods);
    }
    /**
     * 颜色、尺寸返回接口
     * @param entity
     */
    @Override
    public void SelGoodsValuesSuccess(SelGoodsValuesEntity entity) {
        selGoodsValuesEntity = entity;
    }

    /**
     * 加入购物车返回接口
     * @param entity
     */
    @Override
    public void AddCarSuccess(AddCarEntity entity) {
        Toast.makeText(getContext(), entity.msg, Toast.LENGTH_SHORT).show();
        p.request(user_id, "1");
        addcar_pop.dismiss();
    }

    /**
     * 移入收藏夹返回接口
     * @param entity
     */
    @Override
    public void CollectionSuccess(CollectionEntity entity) {
        Log.e("tt", "购物车 -> 移入收藏夹返回接口 ->  " + entity.msg);
        if ("1".equals(entity.statues)){
            endCollection++;
            if (startCollection == endCollection){
                for (CarListEntity.ValuesBean valuesBean : list){
                    if ("1".equals(valuesBean.shop_select)) {
                        ContentValues values_like = new ContentValues();
                        values_like.put("goodsid", valuesBean.goods_id);
                        values_like.put("goods_img", valuesBean.car_path);
                        values_like.put("goods_name", valuesBean.shop_name);
                        values_like.put("goods_price", valuesBean.shop_price);
                        USerService.getInstance().insert("collection", values_like);
                    }
                }

                for (int i = 0; i < headAdapter.getData().size(); i++){
                    if ("1".equals(headAdapter.getData().get(i).shop_select)){
                        headAdapter.getData().remove(i);
                        //i=0;
                        i--;
                    }
                }
                headAdapter.notifyDataSetChanged();
                if (headAdapter.getData().size() <= 0){
                    tv_car_list_bj_wc.setVisibility(View.GONE);
                    ll_car_list_values.setVisibility(View.GONE);
                    ll_item_head_car_list_1.setVisibility(View.GONE);
                    ll_item_head_car_list_0.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @Override
    public void showDialog() {
    }

    @Override
    public void hideDialog() {
    }
    /**
     * 判断是否是全选 并 计算总价
     */
    private void isQXorSumPrice(){
        boolean qx= true ;
        double sumPrice = 0;

        for (CarListEntity.ValuesBean bean : list){
            if (!"1".equals(bean.shop_select)){
                qx = false;
                headAdapter.notifyDataSetChanged();
            }else{
                sumPrice += (Double.parseDouble(bean.shop_price) * Integer.parseInt(bean.shop_num));
            }
        }
        if (qx){
                cbqx=true;
                cb_car_list_qx.setChecked(true);

        }else if(!qx){
            for (CarListEntity.ValuesBean bean : list){
                cb_car_list_qx.setChecked(false);
            }
            cb_car_list_qx.setChecked(false);
        }else{
            cb_car_list_qx.setChecked(false);
            headAdapter.notifyDataSetChanged();
        }
        headAdapter.notifyDataSetChanged();
        tv_item_head_car_list_sum_price.setText("总计￥" + sumPrice + "=商品金额￥" + sumPrice);
        tv_car_list_sumprice.setText("总计:￥" + sumPrice);
        price=sumPrice+"";

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_car_list_back:
                getActivity().finish();
                break;
            case R.id.tv_car_list_bj_wc:
                bj_wc = !bj_wc;
                if (bj_wc){//变成完成
                    tv_car_list_bj_wc.setText("完成");
                    btn_car_list_account.setText("删除");
                    ll_car_list_price.setVisibility(View.GONE);
                    ll_car_list_save.setVisibility(View.VISIBLE);
                }else{//变成编辑
                    tv_car_list_bj_wc.setText("编辑");
                    btn_car_list_account.setText("结算");
                    ll_car_list_price.setVisibility(View.VISIBLE);
                    ll_car_list_save.setVisibility(View.GONE);
                    isQXorSumPrice();
                }
                break;
            case R.id.btn_car_list_account:

                if (bj_wc){//删除
                    for (int i = 0; i < headAdapter.getData().size(); i++){
                        if ("1".equals(headAdapter.getData().get(i).shop_select)){
                            headAdapter.getData().remove(i);
                            i=0;
                        }
                    }
                    headAdapter.notifyDataSetChanged();
                }else{
//                    Intent intent = new Intent(getContext(), PayDemoActivity.class);
//                    intent.putExtra("values",price);
//                    startActivity(intent);

                    ArrayList<String> goods_ids = new ArrayList<>();
                    for (CarListEntity.ValuesBean bean : headAdapter.getData()){
                        if ("1".equals(bean.shop_select)){
                            goods_ids.add(bean.goods_id);
                        }
                    }
                    if (goods_ids.size() > 0){
                        Bundle bundle_goods_ids = new Bundle();
                        bundle_goods_ids.putStringArrayList("goods_ids", goods_ids);
                        Intent affirm_order = new Intent(getActivity(), FragmentActivity.class);
                        affirm_order.putExtra("type", "affirm_order");
                        affirm_order.putExtras(bundle_goods_ids);
                        getActivity().startActivity(affirm_order);
                    }


                }
                break;
            case R.id.btn_car_list_add_save://移入收藏夹
                for (CarListEntity.ValuesBean valuesBean : list){
                    if ("1".equals(valuesBean.shop_select)){
                        startCollection++;
                        p.CollectionRequest(user_id, valuesBean.goods_id);
                    }
                }
                break;
            case R.id.iv_item_bottomaddcar_close://取消加入购物车
                addcar_pop.dismiss();
                break;
            case R.id.tv_item_bottom_addcar_num_subtract://减少数量
                int subtract = Integer.parseInt(tv_item_bottom_addcar_num_number.getText().toString().trim());
                if (subtract > 1) {
                    subtract--;
                }
                tv_item_bottom_addcar_num_number.setText("" + subtract);
                break;
            case R.id.tv_item_bottom_addcar_num_add://增加数量
                int add = Integer.parseInt(tv_item_bottom_addcar_num_number.getText().toString().trim());
                add++;
                tv_item_bottom_addcar_num_number.setText("" + add);
                break;
            case R.id.btn_item_bottom_addcar://加入购物车
                if (size >= selGoodsValuesEntity.size.size()) {
                    Toast.makeText(getContext(), "请选择尺寸", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!TextUtils.isEmpty(user_id)) {
                    p.addCarRequest(user_id, goodsBean.goods_id
                            , goodsBean.goods_name
                            , selGoodsValuesEntity.colors.get(color).colorvalues
                            , selGoodsValuesEntity.size.get(size).size_name
                            , tv_item_bottom_addcar_num_number.getText().toString().trim()
                            , goodsBean.goods_discount_price);
                } else {
                    Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }


    //加入购物车底部弹出窗体
    public void addcar_popupwindow(CarListEntity.RecommendGoodsBean recommendGoodsBean) {
        //加入购物车控件
        //TODO 1:实例化对象
        addcar_pop = new PopupWindow(getActivity());
        //TODO 2：设置属性
        View view_addcar = LayoutInflater.from(getActivity()).inflate(R.layout.item_bottom_addcar, null);
        //初始化控件
        ImageView iv_item_bottom_addcar_img = view_addcar.findViewById(R.id.iv_item_bottom_addcar_img);
        TextView tv_item_bottom_addcar_goods_discount_price = view_addcar.findViewById(R.id.tv_item_bottom_addcar_goods_discount_price);
        MyTextViewHomeOriginalPrice tv_item_bottom_addcar_goods_original_price = view_addcar.findViewById(R.id.tv_item_bottom_addcar_goods_original_price);
        TextView tv_item_bottom_addcar_goods_color = view_addcar.findViewById(R.id.tv_item_bottom_addcar_goods_color);
        tv_item_bottom_addcar_goods_size = view_addcar.findViewById(R.id.tv_item_bottom_addcar_goods_size);
        TextView tv_item_bottom_addcar_goods_color_select = view_addcar.findViewById(R.id.tv_item_bottom_addcar_goods_color_select);
        tv_item_bottom_addcar_num_number = view_addcar.findViewById(R.id.tv_item_bottom_addcar_num_number);
        cb_item_bottom_addxar_size_l = view_addcar.findViewById(R.id.cb_item_bottom_addxar_size_L);//L
        cb_item_bottom_addxar_size_xl = view_addcar.findViewById(R.id.cb_item_bottom_addxar_size_XL);//XL
        cb_item_bottom_addxar_size_xxl = view_addcar.findViewById(R.id.cb_item_bottom_addxar_size_XXL);//XXL
        cb_item_bottom_addxar_size_xxxl = view_addcar.findViewById(R.id.cb_item_bottom_addxar_size_XXXL);//XXXL

        //添加点击监听
        view_addcar.findViewById(R.id.iv_item_bottomaddcar_close).setOnClickListener(this);//关闭键
        view_addcar.findViewById(R.id.tv_item_bottom_addcar_num_subtract).setOnClickListener(this);//减按钮
        view_addcar.findViewById(R.id.tv_item_bottom_addcar_num_add).setOnClickListener(this);//增加按钮
        view_addcar.findViewById(R.id.btn_item_bottom_addcar).setOnClickListener(this);//加入按钮+
        //添加多选框监听
        cb_item_bottom_addxar_size_l.setOnCheckedChangeListener(this);//L
        cb_item_bottom_addxar_size_xl.setOnCheckedChangeListener(this);//XL
        cb_item_bottom_addxar_size_xxl.setOnCheckedChangeListener(this);//XXL
        cb_item_bottom_addxar_size_xxxl.setOnCheckedChangeListener(this);//XXXL


        //控件赋值
        //图片
        Glide.with(getContext()).load(API.BaseUrl + recommendGoodsBean.goods_img_path);
        //价钱
        tv_item_bottom_addcar_goods_discount_price.setText("￥" + recommendGoodsBean.goods_discount_price);
        tv_item_bottom_addcar_goods_original_price.setText("￥" + recommendGoodsBean.goods_original_price);
        //颜色
        color = (int) (Math.random() * (selGoodsValuesEntity.colors.size() - 1));
        tv_item_bottom_addcar_goods_color.setText("已选 : " + selGoodsValuesEntity.colors.get(color).colorvalues);
        tv_item_bottom_addcar_goods_color_select.setText(selGoodsValuesEntity.colors.get(color).colorvalues);


        addcar_pop.setContentView(view_addcar);
        addcar_pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        addcar_pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        //设置点击外部消失
        addcar_pop.setOutsideTouchable(true);
        //TODO 3:展示
        /**
         * @param parent 父布局
         * @param gravity gravity可以是Gravity.TOP、Gravity.BOTTOM、Gravity.LEFT、Gravity.RIGHT。。。。
         * @param x x轴偏移量
         * @param y y轴偏移量
         */
        View parent = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_goods_values, null);
        addcar_pop.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
    }
    //多选按钮组监听
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_item_bottom_addxar_size_L:
                if (isChecked) {
                    size = 0;
                    cb_item_bottom_addxar_size_xl.setChecked(false);
                    cb_item_bottom_addxar_size_xxl.setChecked(false);
                    cb_item_bottom_addxar_size_xxxl.setChecked(false);
                }
                break;
            case R.id.cb_item_bottom_addxar_size_XL:
                if (isChecked) {
                    size = 1;
                    cb_item_bottom_addxar_size_l.setChecked(false);
                    cb_item_bottom_addxar_size_xxl.setChecked(false);
                    cb_item_bottom_addxar_size_xxxl.setChecked(false);
                }
                break;
            case R.id.cb_item_bottom_addxar_size_XXL:
                if (isChecked) {
                    size = 2;
                    cb_item_bottom_addxar_size_l.setChecked(false);
                    cb_item_bottom_addxar_size_xl.setChecked(false);
                    cb_item_bottom_addxar_size_xxxl.setChecked(false);
                }
                break;
            case R.id.cb_item_bottom_addxar_size_XXXL:
                if (isChecked) {
                    size = 3;
                    cb_item_bottom_addxar_size_l.setChecked(false);
                    cb_item_bottom_addxar_size_xl.setChecked(false);
                    cb_item_bottom_addxar_size_xxl.setChecked(false);
                }
                break;
        }
        if (!cb_item_bottom_addxar_size_l.isChecked() && !cb_item_bottom_addxar_size_xl.isChecked() && !cb_item_bottom_addxar_size_xxl.isChecked() && !cb_item_bottom_addxar_size_xxxl.isChecked()) {
            tv_item_bottom_addcar_goods_size.setText("");
            size = selGoodsValuesEntity.size.size();
        } else {
            tv_item_bottom_addcar_goods_size.setText("、 " + selGoodsValuesEntity.size.get(size).size_name);
        }
    }
}
